package com.wn.service.impl;

import com.wn.bean.MenuVo;
import com.wn.bean.Permission;
import com.wn.mapper.PermissionMapper;
import com.wn.service.IMenuService;
import com.wn.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    private IPermissionService permissionService;

    @Override
    public List<MenuVo> queryMenuByUsername(String username) {

        //获取所有的权限里列表
        List<Permission> permissions = permissionService.queryPermissionByUsername(username);
        //把权限列表转成 菜单
        //封装一级菜单
        List<MenuVo> oneMenuVoList = new ArrayList<>();

        for (Permission permission : permissions) {

            if (permission.getLevel().equals(1)) {
                //一级菜单
                MenuVo menuVo = new MenuVo();
                menuVo.setId(permission.getId());
                menuVo.setTitle(permission.getPname());
                menuVo.setPath(permission.getSort() + "");
                menuVo.setLinkUrl(permission.getUrl());
                menuVo.setIcon(permission.getIcon());
                List<MenuVo> childRenMenu = permissions.stream()
                        .filter(per->per.getParentId().equals(permission.getId()))
                        .map(p -> {
                            MenuVo m = new MenuVo();
                            m.setId(p.getId());
                            m.setTitle(p.getPname());
                            m.setPath(p.getSort() + "");
                            m.setLinkUrl(p.getUrl());
                            m.setIcon(p.getIcon());
                            return m;
                        }).collect(Collectors.toList());
                //设置子菜单
                menuVo.setChildren(childRenMenu);
                oneMenuVoList.add(menuVo);
            }
        }
        return oneMenuVoList;
    }
}